﻿#region Librerias

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using ESF.General;

#endregion


namespace ESF.Web.Handlers
{
	public class GetFile : IHttpHandler
	{
		#region Metodos de IHttpHandler

		public bool IsReusable
		{
			get { return false; }
		}


		public void ProcessRequest(HttpContext pContext)
		{
			string fileName;
			string eTag;

			FileInfo fileInfo;


			fileName = pContext.Request.QueryString ["pFileName"];

			if (TextHelper.IsEmpty (fileName))
			{
				pContext.Response.StatusDescription = "pFileName not provided";
				return;
			}

			try
			{
				fileName = TextHelper.DecryptRSA (fileName);
			}
			catch (Exception)
			{
				pContext.Response.StatusDescription = "pFileName is invalid";
				return;
			}

			if (!File.Exists (fileName))
			{
				pContext.Response.StatusCode = (int) HttpStatusCode.NotFound;
				pContext.Response.StatusDescription = string.Format ("The file {0} was not found", Path.GetFileName (fileName));
				return;
			}

			ModuleHandlerHelper.AddESFDescriptionHeader(pContext, "GetFile"); 
			
			if (ModuleHandlerHelper.GeneratedResponse_SetETagCacheIs304File(pContext, fileName, null, 60, out fileInfo, out eTag))
			{
				return;
			}

			ModuleHandlerHelper.AddZipFilter(pContext);

			pContext.Response.AddHeader ("Content-Disposition", string.Format ("inline;filename={0}", Path.GetFileName (fileName)));
			
			pContext.Response.BinaryWrite (File.ReadAllBytes(fileName));
		}

		#endregion
	}
}
